package com.wstuo.dwr;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.wstuo.common.tools.entity.InstantMessage;
import com.wstuo.common.tools.service.IInstantMessageService;

/**
 * 反转信息
 * @author WSTUO
 *
 */

public class GetUserPageDwr{
	private static final Logger LOGGER = Logger.getLogger(GetUserPageDwr.class);
	@Autowired
	private IInstantMessageService instantmessageService;
	public static Set<Long> onlineUsers =new ConcurrentSkipListSet<Long>();
	
	
	/**
	 * 页面提示加载
	 * @param userId
	 */
	public void onPageLoad(Long userId) {
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("userId", userId);
		DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();
		try {
			dwrScriptSessionManagerUtil.init();
		} catch (ServletException e) {
			LOGGER.error(e);
		}
		onlineUsers.add(userId);
	}

	/**
	 * 自动推送信息
	 */
	public void sendMessageAuto() {
		//获得WEB上下文  
        for(final Long userId:onlineUsers){
        	final List<InstantMessage> lis=instantmessageService.findByUserId(userId);
        	if(lis!=null && lis.size()>0 && lis.get(0).getDwrStatus().equals("0")){
        		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
        			public boolean match(ScriptSession session) {
        				if (session.getAttribute("userId") == null)
        					return false;
        				else
        					return (session.getAttribute("userId")).equals(userId);
        			}
        		}, new Runnable() {
        			private ScriptBuffer script = new ScriptBuffer();

        			public void run() {
        				script.appendScript("userAssgin.userAssginOut(");
        				script.appendData(lis);
        				script.appendScript(")");
        				Collection<ScriptSession> sessions = Browser
        						.getTargetSessions();
        				for (ScriptSession scriptSession : sessions) {
        					scriptSession.addScript(script);
        				}
        			}
        		});
        		instantmessageService.updateDwrSendStatus(lis);
        	}else{
        		continue;
        	}
		}
        
	}
}